package com.hanserwei.community.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanserwei.community.entity.po.Role;
import com.hanserwei.community.entity.vo.UserRoleVO;
import com.hanserwei.community.enums.ResponseCodeEnum;
import com.hanserwei.community.exception.ApiException;
import com.hanserwei.community.mapper.RoleMapper;
import com.hanserwei.community.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final RoleMapper roleMapper;

    @Override
    public Boolean addUserRole(Integer userId, Integer roleId) {
        // 查询是否已经存在该用户角色关系
        List<UserRoleVO> list = roleMapper.listUserRole();
        for (UserRoleVO userRoleVO : list) {
            if (userRoleVO.getUserid().equals(userId) && userRoleVO.getRoleId().equals(roleId)) {
                throw new ApiException(ResponseCodeEnum.INVALID_PARAMETER, "该用户已绑定该角色！");
            }
        }
        return roleMapper.addUserRole(userId, roleId);
    }

    @Override
    public List<UserRoleVO> listUserRole() {
        return roleMapper.listUserRole();
    }

    @Override
    public Boolean deleteUserRole(Integer userId, Integer roleId) {
        return roleMapper.deleteUserRole(userId, roleId);
    }

    @Override
    public void deletRoleById(Integer id) {
        // 先查询是否有用户绑定了该角色
        List<UserRoleVO> list = roleMapper.listUserRole();
        for (UserRoleVO userRoleVO : list) {
            if (userRoleVO.getRoleId().equals(id)) {
                throw new ApiException(ResponseCodeEnum.INVALID_PARAMETER, "该角色有用户绑定，请先解除绑定！");
            }
        }
        roleMapper.deleteById(id);
    }
}
